package com.elaticsearch.doc;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/**
 * @author:左泽林
 * @date:日期:2021-08-28-时间:15:35
 * @message:
 */
public class doc_Insert {
    public static void main(String[] args) throws IOException {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("172.20.17.43",9200,"http"))
        );

        try {
            //插入数据
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.index("user").id("1001");
            User user = new User();
            user.setName("张三");
            user.setAge(20);
            user.setSex("男");

            //向es插入数据，必须将数据转换为json数据
            ObjectMapper mapper = new ObjectMapper();
            String userJson = mapper.writeValueAsString(user);
            indexRequest.source(userJson, XContentType.JSON);

            IndexResponse response = esClient.index(indexRequest, RequestOptions.DEFAULT);

            System.out.println("===============操作结果==============");
            System.out.println(response.getResult());
            System.out.println("===============操作结果==============");
        }catch (Exception e){
            System.out.println(e);
        }finally {
            esClient.close();
        }

    }
}
